import re
import string

import psutil
import win32api
import win32com
import win32con
import win32security


def get_token(pid):
    process = win32api.OpenProcess(win32con.PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
    process_token = win32security.OpenProcessToken(process, win32con.TOKEN_QUERY)
    return process_token


def get_pid(name):
    newpidcnt = 0
    pid = 0
    wmi = win32com.client.GetObject('winmgmts:')
    for win32_process_instance in wmi.InstancesOf('win32_process'):
        if win32_process_instance.Name and win32_process_instance.Name.upper() == name.upper():
            pTime = win32_process_instance.Properties_('CreationDate').Value
            processId = int(win32_process_instance.Properties_('ProcessId'))
            if pTime > 5:
                newpidcnt = newpidcnt + 1
                pid = processId
    if newpidcnt > 2:
        raise RuntimeError("error")
    print(pid)
    return pid


def get_pid2(name):
    process_list = psutil.get_process_list()
    regex = "pid=(\d+),\sname=\'" + name + "\'"

    for line in process_list:
        process_info = str(line)
        ini_regex = re.compile(regex)
        result = ini_regex.search(process_info)
        if result is not None:
            pid = string.atoi(result.group(1))
            print(result.group())
            return pid
